# 有语的第一个项目实践，外星人大战项目
# 第四章，为了简化游戏内容，对主函数进行精简后将影响可读性的函数重构后的储存位置
# 22/9/8
import pygame
import sys
from time import sleep

import game_stats
from alien import Alien
from bullet import Bullet
from button import Button
from game_stats import GameStats
from scoreboard import Scoreboard


class GameFunctions:
    def __init__(self, ai_game):
        self.screen = ai_game.screen
        self.bg_color = ai_game.bg_color
        self.ship = ai_game.ship
        self.moving_right = ai_game.ship.moving_right
        self.bullets = ai_game.bullets
        self.settings = ai_game.settings
        self.aliens = ai_game.aliens
        self._create_fleet()
        self.alien_speed = ai_game.settings.alien_speed
        self.game_stats = GameStats(ai_game)

        self.score = Scoreboard(ai_game, self.game_stats)
        self.score_str = int(self.score.score_str)
        self.high_score_str = int(self.score.high_score)
        self.play_button = Button(ai_game, "Play")


    def check_events(self):
        """get()监视键盘和鼠标的动作，当发生事件pygame.QUIT时，执行sys.exit()来退出整个程序"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                # 获取鼠标点击动作的坐标位置
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_play_button(self, mouse_pos):
        """在玩家点击开始按钮后开始新游戏"""
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.game_stats.game_active:
            self.settings.initialize_dynamic_settings()
            self.game_stats.reset_stats()
            self.score_str = 0
            self.game_stats.game_active = True

            # 重置游戏积分
            self.score.prep_score(0)
            # 清除多余的子弹和外星人
            self.aliens.empty()
            self.bullets.empty()

            # 创建新的外星人和飞船
            self._create_fleet()
            self.ship.center_ship()

            # 隐藏鼠标光标
            pygame.mouse.set_visible(False)

    def _check_keydown_events(self, event):
        """按下键盘的动作"""
        # 如果按下右方向键，移动标记变为TRUE
        if event.key == pygame.K_RIGHT:
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.ship.moving_left = True
        elif event.key == pygame.K_UP:
            self.ship.moving_top = True
        elif event.key == pygame.K_DOWN:
            self.ship.moving_bottom = True
        elif event.key == pygame.K_SPACE and self.game_stats.game_active:
            self._fire_bullet()
        elif event.key == pygame.K_q:
            sys.exit()

    def _check_keyup_events(self):
        # 如果松开右方向键，移动标记恢复False
        # 如果松开左方向键，移动标记恢复False
        self.ship.moving_right = False
        self.ship.moving_left = False
        self.ship.moving_bottom = False
        self.ship.moving_top = False

    def _check_fleet_edges(self):
        """判断外星人是否抵达边缘"""
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _check_bullet_alien_collisions(self):
        # 完成射杀
        # 高能子弹，无线射杀，使第一个 True 改为 False
        collisions = pygame.sprite.groupcollide(
            self.bullets, self.aliens, True, True
        )
        if collisions:
            for aliens in collisions.values():
                # 将击杀的每一个外星人计入得分
                self.score_str += self.settings.alien_points*len(aliens)
            self.score.prep_score(self.score_str)
            self.score.check_high_score()
        # 当消灭所有的外星人以后，创建新的外星人
        if not self.aliens:
            self.bullets.empty()
            self._create_fleet()
            self.settings.increase_speed()

    def _check_aliens_bottom(self):
        """检查飞船是否到达了屏幕底端"""
        screen_rect = self.screen.get_rect()
        for alien in self.aliens.sprites():
            if alien.rect.bottom >= screen_rect.bottom:
                self._ship_hit()
                break

    def _change_fleet_direction(self):
        """外星人下移一格，改变移动方向"""
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    def _create_fleet(self):
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        # 可容纳的外星人的数量
        available_space_x = self.settings.screen_width - (2 * alien_width)
        # 取整
        number_aliens_x = available_space_x // (2 * alien_width)
        # 计算可容纳的外星人行数，飞船预留空间以及射击预留时间
        ship_height = self.ship.rect.height
        available_space_y = self.settings.screen_high - \
                            (3 * alien_height) - ship_height
        number_rows = available_space_y // (2 * alien_height)

        for rows_number in range(number_rows):
            for aliens_number in range(number_aliens_x):
                self._create_alien(aliens_number, rows_number)

    def _create_alien(self, aliens_number, row_number):
        """创建第一行外星人"""
        alien = Alien(self)
        alien.x = alien.rect.width + alien.rect.width * 2 * aliens_number
        alien.rect.x = alien.x
        alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
        self.aliens.add(alien)

    def update_screen(self):
        """屏幕更新"""
        # 背景
        self.screen.fill(self.bg_color)
        # 飞船
        self.ship.blitme()
        # 子弹
        self.update_bullet()
        # 外星人
        self.aliens.draw(self.screen)
        # 显示得分
        self.score.show_score()
        # 绘制开始按钮
        if not self.game_stats.game_active:
            self.play_button.draw_button()
        # 让最近绘制的屏幕可见
        # 每次飞船移动时会创建一个新屏幕同时擦去旧屏幕
        pygame.display.flip()

    def update_bullet(self):
        # 更新子弹的位置
        self.bullets.update()
        #  删除消失的子弹
        for bullet in self.bullets.copy():
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)
            # print(len(self.bullets))
        # 画出每一个子弹
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        self._check_bullet_alien_collisions()

    def update_alien(self):
        self._check_fleet_edges()
        self.aliens.update()
        # 检测飞船与外星人之间的碰撞
        if pygame.sprite.spritecollideany(self.ship, self.aliens):
            self._ship_hit()
        # 检查外星人位置
        self._check_aliens_bottom()

    def _fire_bullet(self):
        if len(self.bullets) < self.settings.bullets_allowed:
            new_bullet = Bullet(self)
            self.bullets.add(new_bullet)

    def _ship_hit(self):
        """被撞到以后"""
        if self.game_stats.ships_left >= 1:
            # 清除余下的外星人和子弹
            self.game_stats.ships_left -= 1
            self.aliens.empty()
            self.bullets.empty()
            # 创建新的外星人和子弹
            self._create_fleet()
            self.ship.center_ship()
        else:
            self.game_stats.game_active = False
            pygame.mouse.set_visible(True)

        sleep(0.5)
